package com.example.video.common.security.handler;

import com.alibaba.fastjson.JSON;
import com.example.video.common.security.SysUserDetails;
import com.example.video.common.util.JWTUtils;
import com.example.video.common.util.ResponseWrap;
import com.example.video.common.util.ResponseWrapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : yj
 */
@Component
public class JsonAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JWTUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SysUserDetails principal = (SysUserDetails)authentication.getPrincipal();
        String token = jwtUtils.initAccessToken(principal);
        ResponseWrap<Object> error = ResponseWrapUtil.success(token,"认证成功");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(error));
        writer.flush();
    }
}
